package org.career.pdung.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.career.pdung.DAOImpl.UserDAOImpl;
import org.career.pdung.domain.User;
import org.career.pdung.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class UserServiceImpl implements UserService ,UserDetailsService {
	protected static Logger logger = Logger.getLogger("service");
	
	@Resource(name="userDAOImpl")
	private UserDAOImpl userDAOImpl;
	
	public List<User> getAll() {
		logger.debug("Retrieving all user");
		return  userDAOImpl.getAll();
	}
	
	public User get( Integer id ) {
		logger.debug("Retrieving  user id");
		return userDAOImpl.get(id);
	}

	public void add(User user) {
		logger.debug("Adding new user");		
		userDAOImpl.add(user);
	}
	
	public void delete(Integer id) {
		logger.debug("Deleting existing user");
		userDAOImpl.delete(id);
	}
	
	public void edit(User user) {
		logger.debug("Editing existing user");
		userDAOImpl.edit(user);
	}

	public List<User> getUserByEmail(String email) {
		return userDAOImpl.getUserByEmail(email);
	}
	public User getUserByFacebookId(String facebookId) {		
		return  userDAOImpl.getUserByFacebookId(facebookId);
	}
	public User getUserByTwitterId(String twitterId) {		
		return  userDAOImpl.getUserByTwitterId(twitterId);
	}
	public User getUserByLinkedinId(String linkedinId) {		
		return  userDAOImpl.getUserByLinkedinId(linkedinId);
	}
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		return userDAOImpl.loadUserByUsername(username);
	}
	public User getCurrentUser(){
		String userName = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
    	if("anonymousUser".equals(userName)){
    		return null;
    	} else {
    		return getUserByEmail(userName).get(0);
    	}		
	}
}
